package com.bridge.common.utils;


import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class FileUtils {
    /**
     * MultipartFile转File
     * <p>
     * 项目根路径创建临时文件，转换得到File，再删除临时文件
     *
     * @param multipartFile
     * @return
     */
    public static File multiPartFileToFile(MultipartFile multipartFile) throws IOException {
        //获取文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //根目录下生成临时文件
        File file = new File("/tmp/"+originalFilename);
        inputStreamToFile(multipartFile.getInputStream(), file);
        return file;
    }




    private static void inputStreamToFile(InputStream ins, File file) {
        try (OutputStream os = new FileOutputStream(file)) {
            int bytesRead;
            int bytes = 8192;
            byte[] buffer = new byte[bytes];
            while ((bytesRead = ins.read(buffer, 0, bytes)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
